<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { addUser, userExists } from '../services/UserService'
import { createStarfield, showTemporaryMessage } from '../utils/uiUtils'

// 表单数据
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const error = ref('')
const success = ref('')
const isLoading = ref(false)
const router = useRouter()

// 验证用户名格式
const validateUsername = (username) => {
  // 用户名至少3个字符，不超过20个字符
  if (username.length < 3 || username.length > 20) {
    return '用户名长度必须在3-20个字符之间'
  }
  // 用户名只能包含字母、数字和下划线
  if (!/^[a-zA-Z0-9_]+$/.test(username)) {
    return '用户名只能包含字母、数字和下划线'
  }
  return ''
}

// 验证密码格式
const validatePassword = (password) => {
  // 密码至少6个字符
  if (password.length < 6) {
    return '密码长度至少为6个字符'
  }
  // 密码强度检查
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /[0-9]/.test(password)
  if (!hasLetter || !hasNumber) {
    return '密码必须包含字母和数字'
  }
  return ''
}

// 处理注册提交
const handleRegister = async (e) => {
  e.preventDefault()
  
  // 重置消息
  error.value = ''
  success.value = ''
  
  // 表单验证
  if (!username.value || !password.value || !confirmPassword.value) {
    error.value = '请填写所有字段'
    return
  }
  
  // 验证用户名格式
  const usernameError = validateUsername(username.value)
  if (usernameError) {
    error.value = usernameError
    return
  }
  
  // 验证密码格式和强度
  const passwordError = validatePassword(password.value)
  if (passwordError) {
    error.value = passwordError
    return
  }
  
  // 验证两次密码是否一致
  if (password.value !== confirmPassword.value) {
    error.value = '两次输入的密码不一致'
    return
  }
  
  isLoading.value = true
  
  try {
    // 添加用户（使用加密后的密码）
    const result = addUser(username.value, password.value)
    
    if (result.success) {
      success.value = '注册成功！请登录'
      
      // 重置表单
      username.value = ''
      password.value = ''
      confirmPassword.value = ''
      
      // 显示临时成功消息
      showTemporaryMessage('注册成功！即将跳转到登录页面...', (msg) => {
        success.value = msg
      })
      
      // 3秒后跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 3000)
    } else {
      error.value = result.message || '注册失败，请稍后再试'
    }
  } catch (err) {
    console.error('注册失败:', err)
    error.value = '注册过程中发生错误，请稍后再试'
  } finally {
    isLoading.value = false
  }
}

// 返回登录页面
const goToLogin = () => {
  router.push('/login')
}

// 组件挂载和卸载处理
let cleanupMeteors = null

onMounted(() => {
  // 使用工具函数创建星空背景
  cleanupMeteors = createStarfield('star-background')
})

onUnmounted(() => {
  if (cleanupMeteors) {
    cleanupMeteors()
  }
})
</script>

<template>
  <div class="register-container">
    <div class="register-form">
      <h2>用户注册</h2>
      <form @submit="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            type="text"
            v-model="username"
            placeholder="请输入用户名"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            type="password"
            v-model="password"
            placeholder="请输入密码（至少6个字符）"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            type="password"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            class="form-input"
          />
        </div>
        <div v-if="error" class="error-message">{{ error }}</div>
        <div v-if="success" class="success-message">{{ success }}，即将跳转到登录页面...</div>
        <button type="submit" class="register-button" :disabled="isSubmitting">
          <span v-if="isSubmitting">注册中...</span>
          <span v-else>注册</span>
        </button>
      </form>
      <div class="login-link">
        已有账号？<button @click="goToLogin" class="link-button">立即登录</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 星星背景样式 */
.star-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #0a0a2a;
  z-index: -1;
  overflow: hidden;
}

/* 星星样式 */
.star {
  position: absolute;
  background-color: white;
  border-radius: 50%;
  animation: twinkle 2s infinite alternate;
}

@keyframes twinkle {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

/* 流星样式 */
.meteor {
  position: absolute;
  height: 2px;
  background: linear-gradient(90deg, transparent, white, transparent);
  animation: meteor 2s linear forwards;
  pointer-events: none;
}

@keyframes meteor {
  0% {
    transform: rotate(45deg) translateX(-100%);
    opacity: 0;
  }
  10% {
    opacity: 0.8;
  }
  90% {
    opacity: 0.8;
  }
  100% {
    transform: rotate(45deg) translateX(100vw);
    opacity: 0;
  }
}

/* 注册表单样式 */
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #333;
}

.register-form {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  position: relative;
  z-index: 1;
}

.register-form h2 {
  text-align: center;
  color: #2a6a4c;
  margin-bottom: 20px;
  font-size: 28px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 5px rgba(66, 185, 131, 0.3);
}

.error-message {
  color: #d32f2f;
  font-size: 14px;
  margin-top: 5px;
  text-align: center;
}

.success-message {
  color: #2e7d32;
  font-size: 14px;
  margin-top: 5px;
  text-align: center;
}

.register-button {
  width: 100%;
  padding: 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
  margin-top: 15px;
}

.register-button:hover:not(:disabled) {
  background-color: #3aa675;
  transform: translateY(-2px);
}

.register-button:disabled {
  background-color: #666;
  cursor: not-allowed;
  opacity: 0.7;
  transform: none;
}

/* 加载动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.register-button .loading {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.8s ease-in-out infinite;
  margin-right: 8px;
  vertical-align: middle;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.link-button {
  background: none;
  border: none;
  color: #42b983;
  cursor: pointer;
  font-size: inherit;
  padding: 0;
  text-decoration: underline;
}

.link-button:hover {
  color: #3aa675;
}
</style>